package com.zx._03_并发.chapter_04_public;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import lombok.extern.slf4j.Slf4j;

/**
 * 发布对象——对象逸出
 */
@Slf4j
public class Demo_02 {

    private Integer count;

    public static void main(String[] args) {
        // 1.模拟单线程调用
        Demo_02 demo1 = new Demo_02();
        demo1.init();
        log.info("单线程调用={}", demo1.getCount());

        // 2.模拟多线程调用
        Demo_02 demo2 = new Demo_02();
        ExecutorService pool = Executors.newCachedThreadPool();
        pool.execute(() -> demo2.init());//一个线程初始化对象
        pool.execute(() -> log.info("多个线程调用={}", demo2.getCount()));//其他线程调用对象
        pool.execute(() -> log.info("多个线程调用={}", demo2.getCount()));
        pool.execute(() -> log.info("多个线程调用={}", demo2.getCount()));

        pool.shutdown();
    }

    // 模拟初始化对象的方法
    public void init() {
        try {
            log.info("对象创建开始");
            Thread.sleep(2000L);//模拟创建对象很消耗时间
            this.count = 100;
            log.info("对象创建完成");
        } catch (InterruptedException e) {
            log.info("对象创建异常");
        }
    }

    public Integer getCount() {
        if (count == null) {//模拟初始化必须完成才能调用成功这个方法
            throw new NullPointerException("count没有初始化完成");
        }
        return count;
    }

}
